from machine import Pin, PWM
import network
import os
import time
import socket
import gc

SSID="360WiFi-yqxbw"                                           #修改为你的WiFi名字
PASSWORD="yqxbw8005"                                       #修改为你的WiFi密码
wlan=None
s=None
led=None

def connectWifi(ssid, passwd):
  global wlan
  wlan=network.WLAN(network.STA_IF)                        #创建一个wlan对象
  wlan.active(True)                                        #激活网络接口
  wlan.disconnect()                                        #断开上次的WiFi连接
  wlan.connect(ssid,passwd)                                #连接WiFi
  while(wlan.ifconfig()[0] == '0.0.0.0'):
    time.sleep(1)
  return True
def ajaxWebserv():
  #控制Webserver中最小的Ajax
  global s,led
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)    #创建套接字
  s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)  #设置给定套接字选项的值
  s.bind((wlan.ifconfig()[0], 80))                         #绑定IP地址和端口号
  s.listen(1)                                              #监听套接字
  while True:
    conn, addr = s.accept()                                #接受一个连接，conn是一个新的socket对象
    #print("Got a connection from %s" % str(addr))
    request = conn.recv(1024)                              #从套接字接收1024字节的数据
    conn.sendall('HTTP/1.1 200 OK\nConnection: close\nServer: FireBeetle\nContent-Type: text/html\n\n')

    request = str(request)
    ib = request.find('Val=')                              #find the string 'Val=' from request
    if ib > 0 :
      ie = request.find(' ', ib)                           #init address of the index with ib,then find ' '
      Val = request[ib+4:ie]                               #get the string of ib+4 to ie in the request
      print("Val =", Val)
      led.duty(int(Val) * 100)                             #设置LED占空比
      conn.send(Val)                                       #发送数据
    else:
      with open('test.htm', 'r') as html:               #以只读方式打开webCtrl.htm文件
        conn.sendall(html.read())                          #读取并发送webCtrl.htm中的数据
    conn.sendall('\r\n')
    conn.close()                                           #关闭文件
    #print("Connection wth %s closed" % str(addr))

#捕获异常，如果意外中断停止运行程序
try:
  led=PWM(Pin(2), freq=100)                                #创建LED对象
  led.init()
  led.duty(0)
  connectWifi(SSID, PASSWORD)
  ajaxWebserv()                                            #
except:
  if (s):
    s.close()                                              #关闭套接字
  led.deinit()                                             #熄灭LED灯
  wlan.disconnect()                                        #断开WiFi连接
  wlan.active(False)                                       #冻结网络接口#hardware platform: FireBeetle-ESP8266

import time
from machine import Pin
led=Pin(2,Pin.OUT)          #create LED object from pin2,Set Pin2 to output

while True:
  led.value(1)              #turn off
  time.sleep(0.5)
  led.value(0)              #turn on
  time.sleep(0.5)

